<script lang="ts" setup>
import {onMounted, ref} from "vue";
import {addGoods, deleteGoods, getAllGoods, updateGoods, uploadGoodsImg} from "@/request/api/Posts";
import {ElMessage, UploadFile, UploadProps} from "element-plus";
import {Plus} from '@element-plus/icons-vue'
import {BASE_GOODSIMG_URL} from "@/constant/module/file";

const tableData = ref([])
const isAddActive = ref(false);
const isUpdateActive = ref(false);
//修改药品信息
const medicineToUpdate = ref({} as any);
const medicineToAdd = ref({} as any);

const handleEdit = async (medicine: any) => {
  console.log(medicine);
  isUpdateActive.value = true;
  medicineToUpdate.value = {
    id: medicine.id,
    goodsName: medicine.goodsName,
    productDescription: medicine.productDescription,
    price: medicine.price,
    number: medicine.number,
    goodsImg: medicine.goodsImg
  };
};
// 修改商品
const update = async () => {
  try {
    updateGoods(medicineToUpdate.value).then(async (res: any) => {
      console.log(medicineToUpdate.value);
      ElMessage.success(res.data)
      // 清空添加药品的临时对象
      medicineToUpdate.value = {};
      isUpdateActive.value = false;
      init()
    }).catch((err: any) => {
      ElMessage.error('修改失败')
    });
  } catch (error) {
    console.error('修改药品时发生错误:', error);
  }
}
// 删除药品
const handleDelete = async (medicine: any) => {
  try {
    console.log(medicine.id);
    deleteGoods(medicine.id).then((res: any) => {
      ElMessage.success(res.data)
      init()
    }).catch((err: any) => {
      ElMessage.error('删除失败')
    });
  } catch (error) {
    console.error('网络错误，请稍后再试');
  }
}
//增加药品
const showAddMedicineForm = () => {
  isAddActive.value = true;
  // 重置添加药品的临时对象
  medicineToAdd.value = {
    goodsName: '',
    productDescription: '',
    price: 0,
    number: 0,
    goodsImg: ''
  }
};
const submitAddMedicine = async () => {
  try {
    addGoods(medicineToAdd.value).then((res: any) => {
      ElMessage.success(res.data)
      // 清空添加药品的临时对象
      medicineToAdd.value = {};
      isAddActive.value = false;
      init()
    }).catch((err: any) => {
      ElMessage.error('添加失败')
    });
  } catch (error) {
    console.error('添加药品时发生错误:', error);
  }
};
// 获取数据
const init = async () => {
  getAllGoods().then((res: any) => {
    tableData.value = res.data
    console.log('res', res)
  })
}

const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const uploadChange = (file: UploadFile) =>{
  let fd = new FormData()
  fd.append('uploadFile', file.raw!)
  uploadGoodsImg(fd).then((res: any) => {
    console.log('图片上传到' + res)
    dialogImageUrl.value =BASE_GOODSIMG_URL + res
    medicineToAdd.value.goodsImg = dialogImageUrl.value
    console.log(dialogImageUrl.value)
  })
}

const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles)
}

const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!
  dialogVisible.value = true
}

onMounted(() => {
  init()
})
</script>

<template>
  <el-button style="margin-right: 0;margin-top: 4px" @click="showAddMedicineForm">添加药品</el-button>

  <div class="about">
    <el-table :data="tableData" style="width: 100%">
      <el-table-column type="selection" width="55"/>
      <el-table-column prop="id" label="商品id" width="180"/>
      <el-table-column prop="id" label="商品图片" width="180">
        <template #default="scope">
          <div class="demo-image">
            <div class="block">
              <el-image style="width: 100px; height: 100px" :src="scope.row.goodsImg" fit="cover" />
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="goodsName" label="商品名" width="180"/>
      <el-table-column prop="productDescription" label="商品简介"/>
      <el-table-column prop="price" label="价格"/>
      <el-table-column prop="number" label="数量"/>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.row)"
          >修改
          </el-button
          >
          <el-button
              size="small"
              type="danger"
              @click="handleDelete(scope.row)"
          >删除
          </el-button
          >
        </template>
      </el-table-column>
    </el-table>
  </div>
<!--  药品添加-->
  <el-dialog v-model="isAddActive" width="50%">
    <el-form :model="medicineToAdd" ref="addMedicineForm" label-width="120px">
      <el-header>添加药品</el-header>
      <el-form-item label="药品名称">
        <el-input v-model="medicineToAdd.goodsName"></el-input>
      </el-form-item>
      <el-form-item label="药品介绍">
        <el-input v-model="medicineToAdd.productDescription"></el-input>
      </el-form-item>
      <el-form-item label="药品单价">
        <el-input v-model.number="medicineToAdd.price"></el-input>
      </el-form-item>
      <el-form-item label="药品库存">
        <el-input v-model.number="medicineToAdd.number"></el-input>
      </el-form-item>
      <el-form-item label="药品图片">
        <el-upload
            action="#"
            list-type="picture-card"
            :on-change="uploadChange"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :auto-upload=false
            :limit="1"
        >
          <el-icon><Plus /></el-icon>
        </el-upload>

        <el-dialog v-model="dialogVisible">
          <img w-full :src="dialogImageUrl" alt="Preview Image" />
        </el-dialog>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitAddMedicine">提交</el-button>
        <el-button @click="isAddActive = false">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>

  <!--  //药品修改-->
  <el-dialog v-model="isUpdateActive" title="药品修改">
    <el-form :model="medicineToUpdate" ref="medicineDetailForm" label-width="120px">
      <el-header>药品修改</el-header>
      <el-form-item label="药品名称">
        <el-input v-model="medicineToUpdate.goodsName"></el-input>
      </el-form-item>
      <el-form-item label="药品介绍">
        <el-input v-model="medicineToUpdate.productDescription"></el-input>
      </el-form-item>
      <el-form-item label="药品单价">
        <el-input v-model.number="medicineToUpdate.price"></el-input>
      </el-form-item>
      <el-form-item label="药品库存">
        <el-input v-model.number="medicineToUpdate.number"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="update">提交</el-button>
        <el-button @click="isUpdateActive = false">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>

</template>

<style>
.about {
  display: flex;
  align-items: center;
}
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.demo-image .block {
  padding: 30px 0;
  text-align: center;
  border-right: solid 1px var(--el-border-color);
  display: inline-block;
  width: 20%;
  box-sizing: border-box;
  vertical-align: top;
}
.demo-image .block:last-child {
  border-right: none;
}
.demo-image .demonstration {
  display: block;
  color: var(--el-text-color-secondary);
  font-size: 14px;
  margin-bottom: 20px;
}
</style>
